<template>
  <div class="home-container">
    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="home-top">
      <el-col :span="6" v-for="(item, index) in statisticData" :key="index">
        <div class="statistic-card">
          <el-statistic :value="item.value" :precision="0" :title="item.title">
            <template #title>
              <div class="statistic-title">
                <span>{{ item.title }}</span>
                <el-tooltip :content="item.tooltip" placement="top">
                  <el-icon><Warning /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <template #prefix v-if="item.prefix">{{ item.prefix }}</template>
          </el-statistic>
          <div class="statistic-footer">
            <div class="footer-item">
              <span>{{ item.compareText }}</span>
              <span :class="item.trend">
                {{ item.rate }}
                <el-icon>
                  <ArrowUp v-if="item.trend === 'up'" />
                  <ArrowDown v-else />
                </el-icon>
              </span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 内容区域 -->
    <el-row :gutter="20" class="home-content">
      <!-- 个人信息卡片 -->
      <el-col :span="12">
        <el-card class="profile-card">
          <div class="profile-header">
            <img :src="userStore.userInfo.avatar" class="avatar" alt="用户头像" />
            <div class="profile-info">
              <h3>{{ userStore.userInfo.name }}</h3>
              <p>{{ getGreeting() }}, 欢迎回来！</p>
            </div>
            <div class="current-time">当前时间: {{ currentTime }}</div>
          </div>
          <div class="profile-stats">
            <div class="stat-item" v-for="(stat, index) in profileStats" :key="index">
              <h4>{{ stat.label }}</h4>
              <p>{{ stat.value }}</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 格言卡片 -->
      <el-col :span="12">
        <el-card class="quote-card">
          <div class="quote-content">
            <h3>每日格言</h3>
            <p class="quote-text">{{ quote }}</p>
            <p class="quote-author">—— 佚名</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 在现有内容下方添加图表行 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>商品销售趋势</span>
              <el-radio-group v-model="salesTimeRange" size="small" @change="updateSalesChart">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="salesChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>商品类别分布</span>
              <el-button-group class="chart-actions">
                <el-button size="small" @click="refreshCategoryData">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </el-button-group>
            </div>
          </template>
          <div ref="categoryChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>用户访问转化</span>
              <el-button-group class="chart-actions">
                <el-button size="small" @click="refreshFunnelData">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </el-button-group>
            </div>
          </template>
          <div ref="funnelChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    <Footer style="margin-top: 20px"></Footer>
  </div>
</template>

<script setup lang="ts">
import Footer from "@/components/reuse/footer.vue";
import { ref, onMounted, onUnmounted, shallowRef } from "vue";
import { useUserStore } from "@/store/user";
import { Warning, ArrowUp, ArrowDown, Refresh } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import type { EChartsOption } from "echarts";

const userStore = useUserStore();
const quote = ref("天在下雨，灯下有伞。人在黑暗，心中有光。");
const currentTime = ref("");

// 统计数据
const statisticData = [
  {
    title: "活跃用户",
    value: 98500,
    tooltip: "当日登录系统的用户数量",
    compareText: "较昨日",
    rate: "24%",
    trend: "up",
  },
  {
    title: "商品总数",
    value: 12790,
    tooltip: "系统中的商品总数量",
    compareText: "本月新增",
    rate: "12%",
    trend: "up",
  },
  {
    title: "总销售额",
    value: 128900,
    tooltip: "商品销售总金额",
    compareText: "较上月",
    rate: "8%",
    trend: "down",
    prefix: "¥",
  },
  {
    title: "新增用户",
    value: 1280,
    tooltip: "本月新注册的用户数量",
    compareText: "较上月",
    rate: "32%",
    trend: "up",
  },
];

// 个人统计数据
const profileStats = [
  { label: "登录天数", value: "33" },
  { label: "项目", value: "2" },
  { label: "团队成员", value: "8" },
];

// 获取问候语
const getGreeting = () => {
  const hour = new Date().getHours();
  if (hour < 6) return "凌晨好";
  if (hour < 9) return "早上好";
  if (hour < 12) return "上午好";
  if (hour < 14) return "中午好";
  if (hour < 17) return "下午好";
  if (hour < 19) return "傍晚好";
  if (hour < 22) return "晚上好";
  return "夜深了";
};

// 更新当前时间
const updateCurrentTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString("zh-CN", {
    hour12: false,
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

let timer: number;

onMounted(() => {
  updateCurrentTime();
  timer = setInterval(updateCurrentTime, 1000);
  initSalesChart();
  initCategoryChart();
  initFunnelChart();
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  clearInterval(timer);
  salesChart.value?.dispose();
  categoryChart.value?.dispose();
  funnelChart.value?.dispose();
  window.removeEventListener("resize", handleResize);
});

// 图表相关
const salesChartRef = ref<HTMLElement>();
const categoryChartRef = ref<HTMLElement>();
const funnelChartRef = ref<HTMLElement>();
const salesChart = shallowRef<echarts.ECharts>();
const categoryChart = shallowRef<echarts.ECharts>();
const funnelChart = shallowRef<echarts.ECharts>();
const salesTimeRange = ref("week");

// 模拟销售数据
const getSalesData = (range: string) => {
  const data = {
    week: {
      dates: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      values: [120, 132, 101, 134, 90, 230, 210],
    },
    month: {
      dates: Array.from({ length: 30 }, (_, i) => `${i + 1}日`),
      values: Array.from({ length: 30 }, () => Math.floor(Math.random() * 200 + 100)),
    },
  };
  return data[range as keyof typeof data];
};

// 模拟类别数据
const getCategoryData = () => {
  return [
    { value: 235, name: "家用电器" },
    { value: 274, name: "食品饮料" },
    { value: 310, name: "服装鞋包" },
    { value: 335, name: "数码产品" },
    { value: 400, name: "其他" },
  ];
};

// 初始化销售趋势图表
const initSalesChart = () => {
  if (salesChartRef.value) {
    salesChart.value = echarts.init(salesChartRef.value);
    updateSalesChart();
  }
};

// 更新销售趋势数据
const updateSalesChart = () => {
  const { dates, values } = getSalesData(salesTimeRange.value);
  const option: EChartsOption = {
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: dates,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: values,
        type: "line",
        smooth: true,
        areaStyle: {
          opacity: 0.3,
        },
        itemStyle: {
          color: "#409EFF",
        },
      },
    ],
  };
  salesChart.value?.setOption(option);
};

// 初始化类别分布图表
const initCategoryChart = () => {
  if (categoryChartRef.value) {
    categoryChart.value = echarts.init(categoryChartRef.value);
    updateCategoryChart();
  }
};

// 更新类别分布数据
const updateCategoryChart = () => {
  const option: EChartsOption = {
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: "center",
    },
    series: [
      {
        name: "商品类别",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: getCategoryData(),
      },
    ],
  };
  categoryChart.value?.setOption(option);
};

// 刷新类别数据
const refreshCategoryData = () => {
  updateCategoryChart();
};

// 添加漏斗图数据生成函数
const getFunnelData = () => {
  return [
    { value: 12000, name: "访问" },
    { value: 8500, name: "注册" },
    { value: 6500, name: "下载App" },
    { value: 4500, name: "活跃用户" },
    { value: 3200, name: "付费用户" },
  ].map((item) => ({
    ...item,
    value: Math.floor(item.value * (0.9 + Math.random() * 0.2)), // 添加随机波动
  }));
};

// 初始化漏斗图
const initFunnelChart = () => {
  if (funnelChartRef.value) {
    funnelChart.value = echarts.init(funnelChartRef.value);
    updateFunnelChart();
  }
};

// 更新漏斗图数据
const updateFunnelChart = () => {
  const option: EChartsOption = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c}",
    },
    legend: {
      top: "bottom",
    },
    series: [
      {
        name: "用户转化",
        type: "funnel",
        left: "10%",
        top: 60,
        bottom: 60,
        width: "80%",
        min: 0,
        max: 12000,
        minSize: "0%",
        maxSize: "100%",
        sort: "descending",
        gap: 2,
        label: {
          show: true,
          position: "inside",
        },
        labelLine: {
          length: 10,
          lineStyle: {
            width: 1,
            type: "solid",
          },
        },
        itemStyle: {
          borderColor: "#fff",
          borderWidth: 1,
        },
        emphasis: {
          label: {
            fontSize: 14,
          },
        },
        data: getFunnelData(),
      },
    ],
  };
  funnelChart.value?.setOption(option);
};

// 刷新漏斗图数据
const refreshFunnelData = () => {
  updateFunnelChart();
};

// 监听窗口大小变化
const handleResize = () => {
  salesChart.value?.resize();
  categoryChart.value?.resize();
  funnelChart.value?.resize();
};
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.home-top,
.home-content {
  margin-bottom: 20px;
}

.statistic-card {
  padding: 20px;
  border-radius: 12px;
  background: var(--el-bg-color);
  box-shadow: var(--el-box-shadow-light);
  transition: all 0.3s ease;
}

.statistic-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--el-box-shadow);
}

.profile-card,
.quote-card {
  height: 100%;
  border-radius: 12px;
  overflow: hidden;
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 24px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}
.profile-info {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
.profile-info h3 {
  margin: 0 0 8px;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

.profile-info p {
  margin: 0;
  color: var(--el-text-color-secondary);
}

.profile-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid var(--el-border-color-lighter);
}

.stat-item h4 {
  margin: 0 0 8px;
  color: var(--el-text-color-secondary);
  font-weight: normal;
}

.stat-item p {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.quote-content {
  padding: 20px;
  text-align: center;
}

.quote-text {
  font-size: 18px;
  line-height: 1.6;
  margin: 20px 0;
  color: var(--el-text-color-primary);
}

.quote-author {
  color: var(--el-text-color-secondary);
  font-style: italic;
}

.statistic-title {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--el-text-color-regular);
}

.statistic-title .el-icon {
  font-size: 14px;
  opacity: 0.7;
}

.statistic-footer {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.footer-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.up {
  color: #67c23a;
  display: flex;
  align-items: center;
  gap: 4px;
}

.down {
  color: #f56c6c;
  display: flex;
  align-items: center;
  gap: 4px;
}

.current-time {
  margin-top: 8px;
  font-size: 20px;
  color: var(--el-text-color-secondary);
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 320px;
}

.chart-actions {
  display: flex;
  gap: 8px;
}
</style>
